# 将markdown文件转换为pdf文件
import os
import subprocess
import sys

def check_command(command):
    """
    检查命令是否可用
    """
    try:
        subprocess.run([command, '--version'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        return True
    except FileNotFoundError:
        return False

def md_to_pdf(md_file_path, pdf_file_path):
    """
    将markdown文件转换为pdf文件
    """
    if not check_command('pandoc'):
        print("错误: 未找到pandoc。请确保已安装pandoc并添加到系统PATH中。")
        print("您可以从以下网址下载pandoc: https://pandoc.org/installing.html")
        sys.exit(1)

    pdf_engines = ['pdflatex', 'xelatex', 'lualatex', 'wkhtmltopdf']
    available_engine = next((engine for engine in pdf_engines if check_command(engine)), None)

    if not available_engine:
        print("错误: 未找到可用的PDF引擎。请安装以下引擎之一：")
        print(", ".join(pdf_engines))
        sys.exit(1)

    try:
        subprocess.run(['pandoc', '-s', md_file_path, '-o', pdf_file_path, f'--pdf-engine={available_engine}'], check=True)
        print(f"转换完成: {pdf_file_path}")
    except subprocess.CalledProcessError as e:
        print(f"转换过程中发生错误: {str(e)}")
    except Exception as e:
        print(f"发生未知错误: {str(e)}")

if __name__ == "__main__":
    md_file = input("请输入markdown文件路径: ")
    pdf_file = input("请输入要保存的pdf文件路径: ")
    md_to_pdf(md_file, pdf_file)